package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.exception.AppException;
import org.example.exception.AppExceptionCodeMsg;
import org.example.pojo.Employee;
import org.example.service.IEmployeeService;
import org.example.util.JwtUtils;
import org.example.util.MD5Utils;
import org.example.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/log")
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @PostMapping("/in")
    public ResultBean login(@RequestBody Employee employee){

        log.info("我在进行登录");
        //整体思路就是先查询员工的姓名
        //如果不存在的话，就直接返回空参数，
        //查询到了然后取出来密码，这里的密码是加密过的
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<Employee>();
        queryWrapper.eq("username",employee.getUsername());

        Employee one = employeeService.getOne(queryWrapper);
        if(one == null){
            throw new AppException(AppExceptionCodeMsg.USERNAME_NOT_EXISTS);
        }
        //这个是从数据库拿过来的，已经加密过的
        String dpassword = one.getPassword();
        //一个参数是从前端传过来的密码，后一个是查询的这个的用户名在数据库的存储到的密码
        //整体思路就是根据前端文本框输入用户名进行查询，查询到了取出来密码
        //然后将输入的密码一起进行加密，然后将两个加密后的密码进行对比
        //如果正确的话，登录成功
        boolean decrypt = MD5Utils.decrypt(employee.getPassword(), dpassword);
        if(!decrypt) {
            throw new AppException(AppExceptionCodeMsg.PASSWORD_ERROR);
        }
        one.setPassword(null);
        one.setSalt(null);

        //程序到这里的时候表示登录成功
        //接下就是携带token了
        String token= JwtUtils.generateToken(one);
        ResultBean resultBean = ResultBean.SUCCESS(one);
        resultBean.setMsg(token);
        return resultBean;
    }
}
